<template>
  <div class="register-container">
    <div class="register-page">
      <h2 style="color: #1a1a1a">注册</h2>

      
      <form @submit.prevent="handleRegister">
        <div class="form-group">
          <label for="account">账号</label>
          <div class="input-wrapper">
            <el-icon class="icon"><User /></el-icon>
            <input
              id="account"
              v-model="formData.account"
              type="text"
              placeholder="请输入账号"
              required
            />
          </div>
        </div>

        <div class="form-group">
          <label for="password">密码</label>
          <div class="input-wrapper">
            <el-icon class="icon"><Lock /></el-icon>
            <input
              id="password"
              v-model="formData.password"
              type="password"
              placeholder="请输入密码"
              required
            />
          </div>
        </div>

        <div class="form-group">
          <label for="confirmPassword">确认密码</label>
          <div class="input-wrapper">
            <el-icon class="icon"><Lock /></el-icon>
            <input
              id="confirmPassword"
              v-model="formData.confirmPassword"
              type="password"
              placeholder="请再次输入密码"
              required
            />
          </div>
        </div>

        <button type="submit" class="register-button">
          <el-icon class="button-icon"><Plus /></el-icon>
          注册
        </button>
        <div class="login-link">
          <span>已有账号？</span>
          <a href="/login">登录</a>
        </div>
      </form>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue';
import { ElMessage } from 'element-plus';
import { User, Lock, Plus } from '@element-plus/icons-vue';
// 导入真实的注册API
import { register } from '../../api/auth';
import { useRouter } from 'vue-router';
import { saveLoginInfo } from '../../utils/auth';

const router = useRouter();

// 表单数据
const formData = ref({
  account: '',
  password: '',
  confirmPassword: ''
});

// 表单验证规则
const validateForm = () => {
  if (!formData.value.account.trim()) {
    ElMessage.error('账号不能为空');
    return false;
  }
  if (formData.value.account.length < 4 || formData.value.account.length > 20) {
    ElMessage.error('账号长度应在4-20个字符之间');
    return false;
  }
  if (!formData.value.password) {
    ElMessage.error('密码不能为空');
    return false;
  }
  if (formData.value.password.length < 6) {
    ElMessage.error('密码长度不能少于6个字符');
    return false;
  }
  if (formData.value.password !== formData.value.confirmPassword) {
    ElMessage.error('两次输入的密码不一致');
    return false;
  }
  return true;
};

// 注册处理函数
const handleRegister = async () => {
  if (validateForm()) {
    try {
      // 调用真实的注册API
      const response = await register(formData.value.account, formData.value.password);
      
      if (response.success) {
        ElMessage.success('注册成功！');
        // 保存token和用户信息
        // 如果后端返回了token，使用返回的token；否则使用临时token
        const token = response.data?.token || `user_token_${Date.now()}`;
        saveLoginInfo(
          token,
          response.data?.id,
          response.data?.account || formData.value.account
        );
        // 注册成功后跳转到首页
        setTimeout(() => {
          router.push('/');
        }, 500);
      } else {
        // 检查是否是账号重复的情况
        const errorMessage = response.message || '';
        if (errorMessage.includes('账号重复') || errorMessage.includes('already exists') || 
            errorMessage.includes('account exists') || errorMessage.toLowerCase().includes('duplicate')) {
          ElMessage.error('该账号已存在，请使用其他账号');
        } else {
          ElMessage.error(errorMessage || '注册失败');
        }
      }
    } catch (error: any) {
      console.error('注册请求失败:', error);
      // 检查错误对象中的message是否包含账号重复的相关信息
      const errorMessage = error.message || '';
      if (errorMessage.includes('账号重复') || errorMessage.includes('already exists') || 
          errorMessage.includes('account exists') || errorMessage.toLowerCase().includes('duplicate')) {
        ElMessage.error('该账号已存在，请使用其他账号');
      } else {
        ElMessage.error(errorMessage || '网络错误，请稍后重试');
      }
    }
  }
};
</script>

<style scoped>
/* 确保html、body和所有元素没有默认边距和padding */
:global(html), :global(body) {
  margin: 0;
  padding: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
}

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.register-container {
  width: 100vw;
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background-image: url("/images/bg.jpg");
  background-size: cover;
  background-position: center;
  background-repeat: no-repeat;
  background-attachment: fixed;
  overflow: hidden;
  position: relative;
  margin: 0;
  padding: 0;
}

.register-page {
  background: rgba(255, 255, 255, 0.5);
  padding: 40px;
  border-radius: 10px;
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.2);
  width: 90%;
  max-width: 400px;
  text-align: center;
  z-index: 10;
}

h1 {
  color: #333;
  margin-bottom: 20px;
}

.form-group {
  margin-bottom: 20px;
  text-align: left;
}

label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

.input-wrapper {
  position: relative;
  width: 100%;
}

.icon {
  position: absolute;
  left: 16px;
  top: 50%;
  transform: translateY(-50%);
  color: #999;
  font-size: 18px;
  z-index: 1;
}

.button-icon {
  margin-right: 8px;
  font-size: 18px;
}

input {
  width: 100%;
  padding: 16px 16px 16px 48px;
  border: 1px solid #ddd;
  border-radius: 5px;
  font-size: 16px;
  transition: border-color 0.3s;
  box-sizing: border-box;
  height: 50px;
}

input:focus {
  outline: none;
  border-color: #667eea;
  box-shadow: 0 0 0 2px rgba(102, 126, 234, 0.2);
}

.error-message {
  display: block;
  color: #e74c3c;
  font-size: 12px;
  margin-top: 5px;
}

.register-button {
    width: 100%;
    padding: 16px;
    background: linear-gradient(135deg, #3a8a4a 0%, #408038 100%);
    color: white;
    border: none;
    border-radius: 5px;
    font-size: 18px;
    font-weight: 500;
    cursor: pointer;
    transition: transform 0.2s, background 0.3s;
    margin-top: 10px;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 55px;
  }

.register-button:hover {
    transform: translateY(-2px);
    background: linear-gradient(135deg, #30753c 0%, #356e30 100%);
  }

.login-link {
  margin-top: 20px;
  font-size: 14px;
  color: #333;
}

.login-link a {
  color: #000000;
  font-weight: bold;
  text-decoration: none;
  margin-left: 5px;
}

.login-link a:hover {
  text-decoration: underline;
  color: #333333;
}

.message {
  margin-top: 20px;
  padding: 10px;
  border-radius: 5px;
  font-size: 14px;
  text-align: center;
}

.message.success {
  background-color: #d4edda;
  color: #155724;
  border: 1px solid #c3e6cb;
}

.message.error {
  background-color: #f8d7da;
  color: #721c24;
  border: 1px solid #f5c6cb;
}
</style>
